
package stcu;

import stcu.forms.*;
import com.nvlled.route.*;
import javax.swing.SwingUtilities;
import java.awt.Window;

public class Client {

    private Client self = this;
    private ObjectRouter router;
    private ClientAuth auth;
    private Prober prober;
    private GroupAccess access;

    LoginForm loginForm;
    MainForm mainForm;

    public Client(ObjectRouter router) {
        this.router = router;
        init();
    }

    private void init() {
        auth = new ClientAuth(router);
        prober = new Prober(router);
        access = new GroupAccess(router);

        loginForm = new LoginForm(auth);
        auth.setLoginHook(new LoginHook());
        auth.setLogoutHook(new LogoutHook());
    }

    public ObjectRouter getRouter() {
        return router;
    }

    public ClientAuth getAuth() {
        return auth;
    }

    public GroupAccess getAccess() {
        return access;
    }

    public void start() {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                loginForm.setVisible(true);
            }
        });
        new Thread(prober).start(); // start probing for servers
    }

    class LoginHook implements Runnable {
        public void run() {
            prober.stop();
            String username = auth.getLoginId();
            Group defaultGroup = access.join(username, "0");
            mainForm = new MainForm(defaultGroup, self);
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    mainForm.setVisible(true);
                    loginForm.setVisible(false);
                }
            });
        }
    }

    class LogoutHook implements Runnable {
        public void run() {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    for (Window w: Window.getWindows()) {
                        w.setVisible(false);
                    }
                }
            });
            router.purgeRoutes();
            init();
            start();
        }
    }

    public static void main(String args[]) throws Exception { 
        ObjectRouter router = new ObjectRouter();
        Client c = new Client(router);
        c.start();

        router.bind();
    }
}

